# (setq py-indent-offset 2)
from java.lang import *
from java.util.concurrent import *
from it.unimi.dsi.webgraph import *
from it.unimi.dsi.law.rank import *
from it.unimi.dsi.law.stat import *
from StringIO import *
import os
import jarray

class RankerTask(Runnable):
  def __init__(self, graph, alpha,
			   iterations, barrier):
	pagerank = PageRank(graph)
	pagerank.alpha = alpha
	pagerank.init()
	self.graph = graph
	self.alpha = alpha
	self.iterations = iterations
	self.barrier = barrier
	self.logger = StringIO('')
	self.pagerank = pagerank
  def run(self):
	print >> self.logger,\
		  '[nodes = %d, links = %d]' % \
		  (self.graph.n, self.graph.m)
	for i in range(self.iterations):
	  self.pagerank.step()
	  if i > 0:
		tau = KendallTau.compute(
		  self.pagerank.rank,
		  self.pagerank.previousRank)
		print >> self.logger,\
			  '[iter = %d, tau = %f]' % \
			  (i + 1, tau)
	self.barrier.await()
	
ITERS = 6
TASKS = 4
bdir = r'C:\packages\jylab-0.2\examples\webmatrix'
relbasename = r'cnr-2000'
basename = os.path.join(bdir, relbasename)
graph = BVGraph.loadOffline(String(basename))
barrier = CyclicBarrier(TASKS + 1)
pool = Executors.newCachedThreadPool()
tasks = []
futures = []
alpha = 0.75

for i in range(TASKS):
  task = RankerTask(graph, alpha, ITERS, barrier)
  tasks.append(task)
  future = pool.submit(task)
  futures.append(future)
  alpha = alpha + 0.05
barrier.await()

print 'Pagerank computation tasks completed'
print '[nodes = %d, links = %d]' % (graph.n, graph.m)
for i in range(TASKS):
  alpha = tasks[i].alpha
  lastlog = tasks[i].logger.getvalue().split('\n')[-2]
  print 'alpha = %.2f : %s' % (alpha, lastlog)  
        

    
        
        
